package com.example.common.tools.text

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

class TextRegularWatcher : TextWatcher {

    /**
     * et
     */
    private var et: EditText? = null

    /**
     * 筛选条件
     */
    private var regex: String? = null


    private var textListener: TextListener? = null

    constructor(et: EditText) : this(et, Regular.NO_SYMBOL_REGEX)

    constructor(et: EditText, regex: String) {
        this.et = et
        this.regex = regex
        addTextChangedListener()
    }

    constructor(et: EditText, regex: String, listener: TextListener) {
        this.et = et
        this.regex = regex
        this.textListener = listener
        addTextChangedListener()
    }

    fun addTextChangedListener() {
        et?.addTextChangedListener(this)
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun afterTextChanged(editable: Editable?) {
        val str: String = editable.toString()
        val inputStr = clearLimitStr(regex!!, str)
        et!!.removeTextChangedListener(this)
        // et.setText方法可能会引起键盘变化,所以用editable.replace来显示内容
        editable?.replace(0, editable.length, inputStr!!.trim())
        et!!.addTextChangedListener(this)
        if (textListener != null) {
            textListener!!.onTextChangede(inputStr)
        }
    }


    /**
     * 清除不符合条件的内容
     *
     * @param regex
     * @return
     */
    private fun clearLimitStr(regex: String, str: String): String? {
        return str.replace(regex.toRegex(), "")
    }


    interface TextListener {
        fun onTextChangede(charSequence: CharSequence?)
    }
}

